//
//  LZVideoCacheManager.m
//  laziz_Consumer
//
//  Created by xbnzd on 17/3/29.
//  Copyright © 2017年 XBN. All rights reserved.
//

#import "LZVideoCacheManager.h"
static int max_save_number = 30;

@interface LZVideoCacheManager()
@end

@implementation LZVideoCacheManager

+ (instancetype)shareManager
{
    static LZVideoCacheManager *m = nil;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        m = [[LZVideoCacheManager alloc] init];
    });
    
    return m;
    
}

#pragma mark - 检查视频url是否已经下载过.下载过的话返回本地的地址.没有的话.原样返回

/**
 检查视频地址是否在本地已经有存储.有的话返回本地的.没有的话,原样返回

 @param videoUrl <#videoUrl description#>
 @param completeBlock <#completeBlock description#>
 */
- (void)checkVideoWithUrl:(NSURL *)videoUrl Completed:(void (^)(NSURL *))completeBlock
{
    NSString *ss = [self returnLocalPathWithVideoURLStr:videoUrl.absoluteString];
    if (ss.length > 0) {
        if (completeBlock) {
            completeBlock([NSURL fileURLWithPath:ss]);
        }
    }else{
        if (completeBlock) {
            completeBlock(videoUrl);
        }
    }
}

#pragma mark - 获取临时存储地址

/**
 获取视频下载时临时存储的地址

 @return <#return value description#>
 */
- (NSString *)getCacheTemporaryPath
{
    NSString *document = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
    NSString *tempP =  [document stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",@"laziztemp.mp4"]];
    DLog(@"====VIDEO-TEMPORARY-PATH=====%@",tempP);
    
    return tempP;
}

#pragma mark - 获取临时文件数据长度

/**
 获取临时文件长度

 @return <#return value description#>
 */
- (NSInteger)getCacheTemporarySize
{
    return (NSInteger)[self returnItemSizeWithPath:[self getCacheTemporaryPath]];
}

#pragma mark - 复制临时存储的视频数据到本地

/**
 复制临时存储的数据到本地
 */
- (BOOL)copyTheTemporaryPathToLocalVideoPathWithVideoURL:(NSString *)urlStr
{
    NSString *tempPath = [self getCacheTemporaryPath];
    
    NSString *p = [NSString stringWithFormat:@"%@/%@-%@-%@",[self getCachePath],[self getAppCurrentVideoCount],[self getAppVersion],[self machVideoFileName:urlStr]];
    NSURL *toPathURL = [NSURL fileURLWithPath:p];
    
    NSError *error;
    [[NSFileManager defaultManager] moveItemAtURL:[NSURL fileURLWithPath:tempPath] toURL:toPathURL error:&error];
    
    NSArray *arr = [self readAllVideos];
    if (arr.count > max_save_number) {
        [self deleteTheFirstVideo];
    }
    
    if (error == nil) {
        return YES;
    }
    
    return NO;
}

#pragma mark -
#pragma mark 删除某一个视频
/**
 删除某一个视频
 
 @param videoUrl 视频url 后台返回的
 @return <#return value description#>
 */
- (BOOL)removeTheLocalVideoWithVideoURL:(NSString *)videoUrl
{
    NSString *fullPath = [self returnTheFullPathWithVideoURLPath:[self machVideoFileName:videoUrl]];
    
    if (fullPath.length > 0) {
        BOOL result = [[NSFileManager defaultManager] removeItemAtPath:fullPath error:nil];
        return result;
    }
    
    return NO;
}


#pragma mark -
#pragma mark =====================以下是私有方法======
#pragma mark - 获取下载完成后,存储本地的地址

/**
 下载结束并且全部下载后.复制到此存储地址
 
 @return <#return value description#>
 */
- (NSString *)getCachePath
{
    NSString *p = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *docP = [NSString stringWithFormat:@"%@/lzmove",p];
    DLog(@"====VIDEO-SAVE-PATH=====%@",docP)
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:docP]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:docP withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    return docP;
}

#pragma mark 对写入的视频进行加工 如果包含/..则去最后的一组字符串作为存入地址
/**
 *  @author Zhoudan, 16-10-24 16:10:41
 *
 *  对存入名称进行加工,如果包含/..则去最后的一组字符串作为存入地址
 *
 */
- (NSString *)machVideoFileName:(NSString *)videoFileName
{
    NSArray *arr = [videoFileName componentsSeparatedByString:@"/"];
    if (arr.count > 0) {
        return arr.lastObject;
    }
    
    return videoFileName;
}

#pragma mark -
#pragma mark 读取目录下所有文件
/**
 *  @author Zhoudan, 16-10-24 13:10:56
 *
 *  读取目录下所有文件
 *
 */
- (NSArray *)readAllVideos
{
    NSString *p = [self getCachePath];

    NSArray *arr = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:p error:nil];
    return arr;
}

#pragma mark -
#pragma mark 删除文件
/**
 *  @author Zhoudan, 16-10-24 16:10:19
 *
 *  默认存储一定的数量.当超过这个数量后,删掉最先存储的那个
 *
 */
- (BOOL)deleteTheFirstVideo
{
    NSString *p = [self getCachePath];
    
    NSArray *arr = [self getAscendingArrWithBaseArr:[self readAllVideos]];
    NSString *firstP = [NSString stringWithFormat:@"%@/%@",p,arr.firstObject];
    BOOL result = [[NSFileManager defaultManager] removeItemAtPath:firstP error:nil];
    return result;
    
}


#pragma mark -
#pragma mark 根据url地址查看本地是否有该视频,有,返回路径,没有的话.返回空字符串
/**
 *  @author Zhoudan, 16-10-24 16:10:27
 *
 *  根据后台返回的下载地址检测本地是否已经有过下载.有的话,返回本地路径.没有返回空字符串`
 *
 */
- (NSString *)returnLocalPathWithVideoURLStr:(NSString *)videoFileName
{
    NSString *baseP = [self getCachePath];
    NSString *fullPath = [self returnTheFullPathWithVideoURLPath:[self machVideoFileName:videoFileName]];
    if (fullPath.length > 0) {
        NSString *videoP = [NSString stringWithFormat:@"%@/%@",baseP,fullPath];
        BOOL result = [[NSFileManager defaultManager] fileExistsAtPath:videoP];
        
        if (result) {
            return videoP;
        }
    }
    
    
    return @"";
}

#pragma mark -
#pragma mark 检测文件大小
/**
 检测文件大小
 
 @param filePath <#filePath description#>
 @return <#return value description#>
 */
- (long long)returnItemSizeWithPath:(NSString*) filePath{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:filePath]){
        
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}


#pragma mark -
#pragma mark 获取app 版本号
- (NSString *)getAppVersion
{
    NSString *v = [[NSBundle mainBundle] infoDictionary][@"CFBundleShortVersionString"];
    
    return v;
}

#pragma mark -
#pragma mark 获取当前app存储数量标记
- (NSString *)getAppCurrentVideoCount
{
    NSArray *arr = [self readAllVideos];
    if (arr.count == 0) {
        return @"1";
    }else{
        NSArray *temp = [self getAscendingArrWithBaseArr:arr];
        NSString *str = temp.lastObject;
        NSArray *pathArrTemp = [str componentsSeparatedByString:@"-"];
        int num = [pathArrTemp.firstObject intValue];
        
        return [NSString stringWithFormat:@"%d",num + 1];
    }
}

#pragma mark -
#pragma mark 根据video名字查找所存储的全名路径

/**
 根据video的地址,查找存储再本地的全名路径

 @param p <#p description#>
 @return <#return value description#>
 */
- (NSString *)returnTheFullPathWithVideoURLPath:(NSString *)p
{
    NSArray *arr = [self readAllVideos];
    for (NSString *str in arr) {
        if ([str containsString:p]) {
            return str;
        }
    }
    
    return @"";
}

#pragma mark -
#pragma mark 获取升序排列的数组
- (NSArray *)getAscendingArrWithBaseArr:(NSArray *)baseArr
{
    NSArray *temp = [baseArr sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        NSString *str1 = (NSString *)obj1;
        NSString *str2 = (NSString *)obj2;
        
        NSArray *ar1 = [str1 componentsSeparatedByString:@"-"];
        NSArray *ar2 = [str2 componentsSeparatedByString:@"-"];
        
        if ([ar1.firstObject intValue] > [ar2.firstObject intValue]) {
            return NSOrderedDescending;
        }else if ([ar1.firstObject intValue] < [ar2.firstObject intValue]){
            return NSOrderedAscending;
        }else{
            return NSOrderedSame;
        }
    }];
    DLog(@"======localVideo==%@",temp);
    
    return temp;
}

@end
